from datetime import timedelta

SECS_PER_MICROSECOND = 1e-6
SECS_PER_DAY = 24.0 * 3600.0

class TimeDelta(timedelta):
    def to_seconds(self):
        return self.days * SECS_PER_DAY + self.seconds + self.microseconds * SECS_PER_MICROSECOND
        
    def day(self):
        return TimeDelta(days=self.days)
        
    def time_of_day(self):
        return TimeDelta(seconds=self.seconds, microseconds=self.microseconds)
        
    def multiply(self, *numbers):
        """Utility method for easing the multiplication of TimeDelta with several numbers.
        Example:
            interval = HOUR.multiply(3, 4)"""
        return tuple(self * n for n in numbers)
        
    def __pos__(self):
        return TimeDelta(self.days, self.seconds, self.microseconds)
        
    def __neg__(self):
        return TimeDelta(-self.days, -self.seconds, -self.microseconds)
        
    def __abs__(self):
        if self.days < 0:
            return -self
        else:
            return +self
            
    def __add__(self, other):
        return TimeDelta(self.days + other.days, 
                         self.seconds + other.seconds, 
                         self.microseconds + other.microseconds)
                         
    def __sub__(self, other):
        return TimeDelta(self.days - other.days, 
                         self.seconds - other.seconds, 
                         self.microseconds - other.microseconds)
                         
    def __mul__(self, number):
        return TimeDelta(self.days * number, 
                         self.seconds * number, 
                         self.microseconds * number)
                         
    def __rmul__(self, number):
        return self.__mul__(number)
        
    def __div__(self, other):
        if isinstance(other, TimeDelta):
            return self.to_seconds() / other.to_seconds()
        else:
            other = float(other)
            return TimeDelta(self.days / other, 
                             self.seconds / other, 
                             self.microseconds / other)
                             
    def __mod__(self, other):
        if not isinstance(other, TimeDelta):
            raise TypeError("mod operation is only defined for two TimeDelta objects")
        if self == other:
            return TimeDelta(0, 0, 0)
        elif self < other:
            return self
        else:
            div = int(self / other)
            return self - (other * div)
            
TimeDelta.ZERO = ZERO = TimeDelta(microseconds=0)
TimeDelta.USEC = USEC = TimeDelta(microseconds=1)
TimeDelta.MSEC = MSEC = 1000 * USEC
TimeDelta.SEC  = SEC  = 1000 * MSEC
TimeDelta.MIN  = MIN  =   60 * SEC
TimeDelta.HOUR = HOUR =   60 * MIN
TimeDelta.DAY  = DAY  =   24 * HOUR
TimeDelta.WEEK = WEEK =    7 * DAY
